package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/15 18:12
 * https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix/
 */
public class Title329 {
    static int[][] max;
    static int MAX;
    static int n, m;

    public static int longestIncreasingPath(int[][] matrix) {
        n = matrix.length;
        m = matrix[0].length;
        max = new int[n][m];
        MAX = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (max[i][j] == 0) {
                    MAX = Math.max(MAX, dfs(matrix, i, j, -1));
                }
            }
        }
        return MAX;
    }

    private static int dfs(int[][] matrix, int i, int j, int preValue) {
        //未超范围、未被访问过、严格递增序列
        if (i < 0 || i >= n || j < 0 || j >= m || matrix[i][j] <= preValue) {
            return 0;
        }
        if (max[i][j] != 0) {
            return max[i][j];
        }
        //上
        int up = dfs(matrix, i - 1, j, matrix[i][j]);
        //下
        int down = dfs(matrix,i + 1, j, matrix[i][j]);
        //左
        int left = dfs(matrix, i, j - 1, matrix[i][j]);
        //右
        int right = dfs(matrix,  i, j + 1, matrix[i][j]);
        //算上自身延伸除去的长度
        max[i][j] = Math.max(Math.max(up, down), Math.max(left, right)) + 1;
        return max[i][j];
    }

    public static void main(String[] args) {
        int[][] arr = {{7,8,9},{9,7,6},{7,2,3}};
        longestIncreasingPath(arr);
        System.out.println(MAX);
    }
}
